PYPI2DEB_BUILD_STAMP_PREFIX = $(DIR_PYPI2DEB_BUILD)/.stamp
PYPI2DEB_BUILD_STAMPS = $(patsubst %,$(PYPI2DEB_BUILD_STAMP_PREFIX)-%,$(PYPI2DEB_PACKAGES))
# options: python or python3 (for package names: python-foo or python3-foo)
PYPI2DEB_PYTHON_PREFIX ?= python3
PYPI2DEB_SIMPLIFIED_PACKAGE_FILES = $(patsubst %,$(DIR_DEBIAN_SIMPLIFIED_PACKAGE_FILES)/$(PYPI2DEB_PYTHON_PREFIX)-%.deb,$(PYPI2DEB_PACKAGES))


.PHONY: help
help: help-pypi2deb

.PHONY: help-pypi2deb
help-pypi2deb:
	@echo "Debian-specific packaging targets:"
	@echo "    dist-pypi2deb"
	@echo "    upload-pypi2deb"
	@echo

.PHONY: dist
dist: dist-pypi2deb

.PHONY: dist-pypi2deb
dist-pypi2deb: $(PYPI2DEB_BUILD_STAMPS)

# create a deb package via py2dsp (requires "pypi2deb")
$(PYPI2DEB_BUILD_STAMP_PREFIX)-%:
	py2dsp --root "$(DIR_PYPI2DEB_BUILD)" --distribution unstable --build "$*"
	ls -tr "$(DIR_PYPI2DEB_BUILD)" | grep "^$*_.*~pypi2deb_$(DEBIAN_BUILD_ARCH)\.changes$$" | tail -n 1 >"$@.new"
	# fail if no "changes" file was created by py2dsp
	[ -s "$@.new" ]
	mv "$@.new" "$@"

.PHONY: dist-deb-packages-directory
dist-deb-packages-directory: $(PYPI2DEB_SIMPLIFIED_PACKAGE_FILES)

# copy packages created via pypi2deb to the simplified debian export directory
$(PYPI2DEB_SIMPLIFIED_PACKAGE_FILES): $(DIR_DEBIAN_SIMPLIFIED_PACKAGE_FILES)/$(PYPI2DEB_PYTHON_PREFIX)-%.deb: $(PYPI2DEB_BUILD_STAMP_PREFIX)-%
	@mkdir -p "$(DIR_DEBIAN_SIMPLIFIED_PACKAGE_FILES)"
	deb_name="$$(sed -n '/^Files:$$/,$$p' "$(DIR_PYPI2DEB_BUILD)/$$(cat "$<")" \
			 | grep -E "$(PYPI2DEB_PYTHON_PREFIX)-$*_.*pypi2deb_($(DEBIAN_BUILD_ARCH)|all)\.deb$$" \
			 | awk '{print $$5}')"; cp "$(DIR_PYPI2DEB_BUILD)/$$deb_name" "$@"

.PHONY: upload
upload: upload-pypi2deb

.PHONY: upload-pypi2deb
upload-pypi2deb: dist-pypi2deb check-dput-config
	@# make sure that 'cat' is not called without arguments (it would read from stdin)
	[ -z "$(PYPI2DEB_BUILD_STAMPS)" ] || for changes_file in $$(cat $(PYPI2DEB_BUILD_STAMPS)); do \
		dput "$(DEBIAN_UPLOAD_TARGET)" "$(DIR_PYPI2DEB_BUILD)/$$changes_file"; \
	done

.PHONY: clean
clean: clean-pypi2deb

.PHONY: clean-pypi2deb
clean-pypi2deb:
	$(RM) -r "$(DIR_PYPI2DEB_BUILD)"
